package util.jobs;

import java.util.Date;
import java.util.List;

import com.sun.org.apache.regexp.internal.recompile;

import ch.bfh.abcm.rems.sensors.tinkerforge.TFSensorType;
import models.CNAverage;
import models.History;
import models.SensorConfig;
import models.SensorData;
import play.Logger;
import play.Play;
import play.jobs.Every;
import play.jobs.Job;
import util.Persistence;

public class HistoryJob extends Job {

    private static final String HISTORY_MAX_OLD_MS = Play.configuration.getProperty("history.max.old.ms",
            String.valueOf(10 * 1000));

    @Override
    public void doJob() throws Exception {
        List<TFSensorType> sensorTypes = SensorConfig.getConfiguredSensorTypeList();
        for (TFSensorType sensorType : sensorTypes) {
            Logger.debug("Create History for Sensortype: %s", sensorType);
            CNAverage lastCNAvaerage = Persistence.getLastCNAvaerage(sensorType);
            if (lastCNAvaerage == null) {
                Logger.error("LastCNA for HistoryJob is null");
                return;
            }
            if (lastCNAisNewEnough(lastCNAvaerage)) {
                saveHistory(sensorType, lastCNAvaerage);
            } else {
                Logger.warn("Last ClusterNodeAverage for Sensortype: %s is to old, dont create a History", sensorType);
            }
        }
    }

    private void saveHistory(TFSensorType sensorType, CNAverage lastCNAvaerage) {
        History h = new History(lastCNAvaerage.getTimestamp(), lastCNAvaerage.getNodeValue(), sensorType);
        Logger.info("Create new History: %s", h);
        h.save();
        Logger.debug("History saved: OK");
    }

    private boolean lastCNAisNewEnough(CNAverage lastCNAverage) {
        long actualTimeStamp = new Date().getTime();
        long maxOldTimestamp = actualTimeStamp - Long.valueOf(HISTORY_MAX_OLD_MS);
        boolean lastCNAisNewEnough = (lastCNAverage.getTimestamp() > maxOldTimestamp);
        Logger.debug("ActualTime: %s  LastCNATime: %s Diff %s LastCNA is new enough: %s ", actualTimeStamp,
                lastCNAverage.getTimestamp(), (actualTimeStamp - lastCNAverage.getTimestamp()), lastCNAisNewEnough);
        return lastCNAisNewEnough;
    }
}
